import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios'
import tools from './tools'
import { ElMessage } from 'element-plus'

const service:AxiosInstance = axios.create({
    baseURL: '/api',
    timeout: 60000,
})
service.interceptors.request.use((config:AxiosRequestConfig) => {
    let token = `bearer ${tools.getCookie('ev-token')}`
    if (token) { 
        if (config.headers) config.headers.Authorization = token
    }
    return config
}, (error) => {
    ElMessage.error({
        message: error,
    })
})
service.interceptors.response.use((response: AxiosResponse) => {
    const { code, msg } = response.data
    if (code === 0) {
        return response.data
    } 
    // 处理业务错误。
    ElMessage.error(msg)
    return Promise.reject(new Error(msg))
}, (error: AxiosError) => {
    // 处理 HTTP 网络错误
    let message = ''
    // HTTP 状态码
    const status = error.response?.status
    switch (status) {
        case 401:
            message = 'token 失效，请重新登录'
            // 这里可以触发退出的 action
            break
        case 403:
            message = '没有权限'
            break
        case 404:
            message = '请求地址错误'
            break
        case 500:
            message = '服务器错误'
            break
        default:
            message = '网络连接故障'
    }
  
    ElMessage.error(message) 
    return Promise.reject(error)
})

export default service